import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:map_launcher/map_launcher.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/base_resp.dart';
import 'package:tracker/common/permission/permission_manager.dart';
import 'package:tracker/pages/home/home/mixin/home_page_mixin.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/pages/home/home/widget/empty_device_widget.dart';
import 'package:tracker/pages/home/location/model/monitor_data_resp.dart';
import 'package:tracker/pages/home/setting/dialog/instant_mode_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/offline_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/simple_command_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/work_mode_dialog.dart';
import 'package:tracker/pages/home/setting/model/command_config_resp.dart';
import 'package:tracker/pages/home/setting/model/get_setting_resp.dart';
import 'package:tracker/pages/home/setting/model/remote_setting_list_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/provider/global_state_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/startup/config/app_start.dart';
import 'package:tracker/startup/config/model/global_config_resp.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/device_utils.dart';
import 'package:tracker/utils/toast_utils.dart';
import 'package:tracker/utils/upgrade_utils.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../../../../common/widget/common.dart';

// 控制中心
class HomePage extends ConsumerStatefulWidget {
  const HomePage({super.key});

  @override
  ConsumerState<HomePage> createState() => _HomePageState();
}

class _HomePageState extends ConsumerState<HomePage>
    with AutomaticKeepAliveClientMixin, HomePageMixin {

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    XLogger.info("didChangeDependencies");
    getMonitorData();
    loadSavedString();

  }


    final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
    late EasyRefreshController _refreshController;
    TimerUtil? _timerUtil;
    final ScrollController _scrollController = ScrollController();


    _buildLoading() {
      return Container(
        alignment: Alignment.center,
        child: CircularProgressIndicator(
          color: AppTheme.themeConfig.primaryColor,
        ),
      );
    }

    /// 内容视图
    Widget _buildBody() {
      DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
      ButtonShowState buttonShow = ref.read(buttonShowProvider);

    hasThing = deviceInfo.imei != null && deviceInfo.imei!.isNotEmpty;
    if (hasThing) {
      return SingleChildScrollView(
        child: Column(
          children: [
            // 设备信息
            Container(
              margin: const EdgeInsets.only(left: 20, right: 10, top: 40),
              child: Column(children: [
                Row(
                  children: [
                    Container(
                      width: 60,
                      padding: const EdgeInsets.all(15),
                      decoration: const BoxDecoration(shape: BoxShape.circle),
                      child: Image(
                        image: AssetImage(
                            getDeviceIcon(monitorData?.deviceStatus)),
                      ),
                    ),
                    const SizedBox(width: 4),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 昵称
                        Text('昵称；${deviceInfo.deviceName}'),
                        Row(
                          children: [
                            // 设备号
                            Text('设备号：${deviceInfo.imei}'),
                            Stack(
                              alignment: Alignment.bottomCenter,
                              children: [
                                GestureDetector(
                                  onTap: () {
                                    _goDeviceInfoPage();
                                  },
                                  child: Text(
                                    // '（${_getBuildDevicesStatusToString()}）设备详情',
                                    '设备详情',
                                    style: TextStyle(
                                      color: AppTheme.themeConfig.primaryColor,
                                      // decoration: TextDecoration.underline,
                                      decorationColor:
                                          AppTheme.themeConfig.primaryColor,
                                    ),
                                  ),
                                ),
                                Container(
                                  width: 80,
                                  height: 1,
                                  color: AppTheme.themeConfig.primaryColor,
                                )
                              ],
                            ),
                          ],
                        ),
                      ],
                    ),
                    // 设备名
                    // GestureDetector(
                    //   onTap: () {
                    //     _goDeviceInfoPage();
                    //   },
                    //   child: Container(
                    //     width: ScreenUtil.getScreenW(context) - 80 - 70,
                    //     child: Text(
                    //       '${deviceInfo.deviceName}',
                    //       style: TextStyle(
                    //         color: AppTheme.themeConfig.primaryTextColor,
                    //         fontSize: 18,
                    //       ),
                    //       maxLines: 1,
                    //       overflow: TextOverflow.ellipsis,
                    //     ),
                    //   ),
                    // ),
                    // 设备状态
                    // _buildDeviceStatus(),
                  ],
                ),
                const SizedBox(
                  height: 10,
                ),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 4),
                  child: Row(
                    children: [
                      _buildBatteryInfo(13),
                      _buildCsqInfo(13),
                    ],
                  ),
                ),
                if (buttonShow.showshengyinbaojing == 1)
                buildMsg(),
                // Row(
                //   children: [
                //     Column(
                //       crossAxisAlignment: CrossAxisAlignment.start,
                //       children: [
                //         // 设备号
                //         GestureDetector(
                //           onTap: () {
                //             _goDeviceInfoPage();
                //           },
                //           child: Text(
                //             '设备号：${deviceInfo.imei}',
                //             style: TextStyle(
                //               color: AppTheme.themeConfig.secondaryTextColor,
                //               fontSize: 12,
                //             ),
                //           ),
                //         ),
                //         // 更新时间
                //         GestureDetector(
                //           onTap: () {
                //             _goDeviceInfoPage();
                //           },
                //           child: Text(
                //             '更新时间：${getDeviceUpdateTime(deviceInfo)}',
                //             style: TextStyle(
                //               color: AppTheme.themeConfig.secondaryTextColor,
                //               fontSize: 12,
                //             ),
                //           ),
                //         ),
                //       ],
                //     ),
                //     // 切换设备
                //     Expanded(
                //       child: Container(
                //         alignment: Alignment.centerRight,
                //         height: 30,
                //         child: ElevatedButton.icon(
                //           onPressed: () {
                //             final userType = ref.watch(userTypeProvider);
                //             if (userType == UserTypeEnum.device) {
                //               ToastUtils.showDeviceLoginDialog(context);
                //             } else {
                //               context.push(RouterManager.deviceList);
                //             }
                //           },
                //           icon: const Icon(
                //             Icons.sync_alt,
                //             size: 16,
                //           ),
                //           label: const Text('切换设备'),
                //           style: ButtonStyle(
                //             backgroundColor: MaterialStateProperty.all(ColorUtils.hexToColor('#ccecff')),
                //             foregroundColor: MaterialStateProperty.all(AppTheme.themeConfig.primaryColor),
                //             elevation: MaterialStateProperty.all(0),
                //             shadowColor: MaterialStateProperty.all(Colors.transparent),
                //             shape: MaterialStateProperty.all(
                //                 RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0))),
                //             padding: MaterialStateProperty.all(const EdgeInsets.only(left: 8, right: 8)),
                //           ),
                //         ),
                //       ),
                //     ),
                //   ],
                // )
              ]),
            ),
            // 网格菜单
            // _buildGridMenuView(),
            _buildCustomGridMenuView(),
            Container(
              height: 300,
            ),
          ],
        ),
      );
    } else {
      return const EmptyDeviceWidget();
    }
  }

  /// 电量
  _buildBatteryInfo(double fontSize) {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);

    if (deviceInfo.batteryPercentage == null) {
      return Container();
    }
    return Row(
      children: [
        Image.asset(
          _getBatteryImage(monitorData?.batteryPercentage),
          width: 28,
          height: 20,
          fit: BoxFit.fitWidth,
        ),
        const SizedBox(width: 4),
        Text('${monitorData?.batteryPercentage ?? ''}%',
            style: TextStyle(
                fontSize: fontSize,
                color: AppTheme.themeConfig.primaryTextColor)),
        const SizedBox(width: 12),
      ],
    );
  }

  /// 根据电量值获取电量图标
  String _getBatteryImage(int? battery) {

  if (monitorData?.chargingStatus == 0) {
    return 'assets/images/home/charging.png';
  }
    if (battery == null) {
      return 'assets/images/home/power20.png';
    }
    if (monitorData?.deviceStatus == 2 && battery < 20) {// 离线
      battery = 0;
    }
    if (battery <= 20) {
      return 'assets/images/home/power20.png';
    } else if (battery <= 40) {
      return 'assets/images/home/power40.png';
    } else if (battery <= 60) {
      return 'assets/images/home/power60.png';
    } else if (battery <= 80) {
      return 'assets/images/home/power80.png';
    } else if (battery <= 100) {
      return 'assets/images/home/power100.png';
    }
    return 'assets/images/home/power100.png';
  }

  /// 信号
  _buildCsqInfo(double fontSize) {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);

    if (deviceInfo.csq == null) {
      return Container();
    }
    return Row(
      children: [
        Image.asset(
          // _getCsqLevelImage(monitorData?.csq),
          "assets/images/location/liuliang.png",
          width: 24,
          height: 16,
          fit: BoxFit.contain,
        ),
        const SizedBox(width: 4),
        Text('${deviceInfo.csq ?? ''}',
            style: TextStyle(
                fontSize: fontSize,
                color: AppTheme.themeConfig.primaryTextColor)),
      ],
    );
  }

  String _getBuildDevicesStatusToString() {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.isNineDevice == true) {
      return '';
    }
    switch (deviceInfo.deviceStatus) {
      case 2:
        return '离线';
      case 1:
        return '在线';
      case 3:
        return '睡眠';
      case 4:
        return '关机';
      default:
        return '未激活';
    }
  }

  Widget _buildDeviceStatus() {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.isNineDevice == true) {
      return _buildDeviceStatusView('在线', '#19be6b');
    }
    switch (deviceInfo.deviceStatus) {
      case 2:
        return _buildDeviceStatusView('离线', '#909399');
      case 1:
        return _buildDeviceStatusView('在线', '#19be6b');
      case 3:
        return _buildDeviceStatusView('睡眠', '#ff9900');
      case 4:
        return _buildDeviceStatusView('关机', '#fa3534');
      default:
        return _buildDeviceStatusView('未激活', '#c8c9cc');
    }
  }

  Widget _buildDeviceStatusView(String text, String color) {
    return Container(
      margin: const EdgeInsets.only(left: 10),
      padding: const EdgeInsets.only(left: 10, right: 10, top: 2, bottom: 2),
      decoration: BoxDecoration(
        color: ColorUtils.hexToColor(color),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Text(
        text,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 12,
        ),
      ),
    );
  }

  Widget _leftIconRightText(String icon, String text,
      {double? height, double? width}) {
    return GestureDetector(
      onTap: () {
        _onMenuToClick(text);
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
        ),
        width: width,
        height: height,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image(
              image: AssetImage(icon),
              width: 40,
            ),
            SizedBox(
              width: 10,
            ),
            Text(
              text,
              style: TextStyle(
                fontSize: 14,
                color: AppTheme.themeConfig.primaryTextColor,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _topIconBottomText(String icon, String text,
      {double? height, double? width, double? iconwidth, double? fontsize}) {
    return GestureDetector(
      onTap: () {
        _onMenuToClick(text);
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(6),
        ),
        width: width,
        height: height,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image(
              image: AssetImage(icon),
              width: iconwidth ?? 40,
            ),
            SizedBox(height: 5),
            Text(
              text,
              style: TextStyle(
                fontSize: fontsize ?? 14,
                color: AppTheme.themeConfig.primaryTextColor,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建网格菜单
  Widget _buildCustomGridMenuView() {
    ButtonShowState buttonShow = ref.read(buttonShowProvider);
    return Container(
      margin: const EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 0),
      // width: double.infinity,
      child: Column(
        children: [
          Row(
            children: [
              if (buttonShow.showzengzhifuwu == 1)
                Expanded(
                flex: 2,
                child: LayoutBuilder(builder:
                    (BuildContext context, BoxConstraints constraints) {
                  return ConstrainedBox(
                    constraints: BoxConstraints(
                      maxHeight: constraints.maxHeight,
                    ),
                    child: _topIconBottomText(
                        "assets/images/home/bigvip.png", "增值服务",
                        height: 155, iconwidth: 120, fontsize: 16),
                  );
                }),
              ),
              SizedBox(width: 5),
              // Expanded(
              //   child:
              Column(
                children: [
                  if (buttonShow.showanfangluyin == 1)
                    _topIconBottomText(
                      "assets/images/home/anfangluyin.png", "安防录音",
                      width: 120, height: 75),
                  SizedBox(height: 5),
                  _topIconBottomText(
                      "assets/images/home/dingweimoshi.png", "定位模式",
                      width: 120, height: 75),
                ],
              ),
              // ),
            ],
          ),
          SizedBox(height: 5),
          Row(
            children: [
              Expanded(
                child: _leftIconRightText(
                    "assets/images/home/liuliangka.png", "流量卡",
                    height: 75),
              ),
              SizedBox(width: 5),
              _topIconBottomText("assets/images/home/dianziweilan.png", "电子围栏",
                  width: 120, height: 75),
            ],
          ),
          SizedBox(height: 5),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Expanded(
                // flex: 2,
                child: _leftIconRightText(
                    "assets/images/home/yijianyufankui.png", "意见与反馈",
                    height: 75),
              ),
              SizedBox(width: 5),
              _topIconBottomText("assets/images/home/yijianchongqi.png", "一键重启",
                  width: 120, height: 75),
            ],
          ),
          SizedBox(height: 5),
          Container(
            padding: EdgeInsets.symmetric(vertical: 5),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(6),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                // 里程统计
                _topIconBottomText(
                    "assets/images/home/lichengtongji.png", "里程统计",
                    fontsize: 12),
                _topIconBottomText(
                    "assets/images/home/yuanchengshezhi.png", "远程设置",
                    fontsize: 12),
                _topIconBottomText(
                    "assets/images/home/guzhangzijian.png", "故障自检",
                    fontsize: 12),
                _topIconBottomText(
                    "assets/images/home/xunchedaohang.png", "寻车导航",
                    fontsize: 12),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildGridMenuView() {
    return Container(
      margin: const EdgeInsets.only(left: 10, right: 20, top: 10, bottom: 0),
      decoration: const BoxDecoration(),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: menuList.length,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          mainAxisSpacing: 20,
          crossAxisSpacing: 20,
          childAspectRatio: 1.0,
        ),
        itemBuilder: (context, index) {
          var menu = menuList[index];
          return GestureDetector(
            onTap: () {
              _onMenuClick(index);
            },
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
              ),
              // height: 50,
              width: double.infinity,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  _buildMenuImage(menu.iconUrl ?? ''),
                  Text(
                    menu.menuName ?? '',
                    style: TextStyle(
                      fontSize: 15,
                      color: AppTheme.themeConfig.primaryTextColor,
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildMenuImage(String url) {
    double width = 48;
    // 图片，判断是网络图片还是本地资源
    if (url.startsWith('http')) {
      return CachedNetworkImage(
        imageUrl: url,
        width: width,
      );
    } else {
      return Image(
        image: AssetImage(url),
        width: width,
      );
    }
  }

  _onMenuToClick(String title) async {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.imei == null || deviceInfo.imei!.isEmpty) {
      ToastUtils.showToast('无设备信息，请先绑定设备或刷新页面获取');
      return;
    }
    // 设备未关机，请开机
    if (deviceInfo.activated == false && deviceInfo.isNineDevice == false) {
      ToastUtils.showSimpleDialog(context,
          title: '提示',
          content: '设备未开机，请开机\n长按开机键3秒或插入充电自动开机',
          confirmTitle: '好的');
      return;
    }
    // 判断是否过期，如果过期，只能打开vip页面、客服页面
    if (deviceInfo.expired == true) {
      print("已经过期");
      if (title != "增值服务") {
        // 提示充钱
        ToastUtils.showBuyVip(context, () {
          var vipMenu = getMenuByCode('vip');
          if (vipMenu != null) {
            openPageByPath("/vipService", "vip");
          }
        });
      } else {
        print("未过期");
        openPageByPath("/vipService", "vip");
      }
      return;
    }
    if (title == "安防录音") {
      //String path =  '/sound';
      //path = '${path}?imei=${deviceInfo.imei}';
      // 判断是打开本地页面还是跳转到web页面
      openPageByPath(RouterManager.recordHistory, 'sound');
    } else if (title == "定位模式") {
      openPageByPath("/workMode", "workMode");
      //   String path =  '/fence'
      //   path = '${path}?imei=${deviceInfo.imei}';
      //   // 判断是打开本地页面还是跳转到web页面
      //   openPageByPath(path, 'fence');
      //
      //
      //
      //   menuName: '定位模式',
      // menuCode: 'workMode',
      // path: '',
      // iconUrl: 'assets/images/home/location.png',
      // orderNum: 70,
      // isTop: false,
    } else if (title == "流量卡") {
      // String path = 'http://www.sukudianzi.com/weixin/recharge/detail?';
      // path = '${path}rType=h5&simIdOrIccid=${deviceInfo.iccid}';
      // XLogger.info('$path');
      // // 判断是打开本地页面还是跳转到web页面
      // if (Platform.isIOS) {
      //   launchUrl(Uri.parse(path));
      // }else {
      //   openPageByPath(path, 'flow-card');
      // }
      String path = '/flow-card';
      path = '${path}?imei=${deviceInfo.imei}';
      openPageByPath(path, 'flow-card');
    } else if (title == "电子围栏") {
      String path = '/fence';
      path = '${path}?imei=${deviceInfo.imei}';
      // 判断是打开本地页面还是跳转到web页面
      openPageByPath(path, 'fence');
    } else if (title == "寻车导航") {
      _navigation();
    } else if (title == "一键重启") {
      _handleRemoteRestart();
    } else if (title == "里程统计") {
      String path = '/mileage-statistics';
      path = '${path}?imei=${deviceInfo.imei}';
      // 判断是打开本地页面还是跳转到web页面
      openPageByPath(path, "mileageStatistics");
    } else if (title == "远程设置") {
      String path = '/remote-setting';
      path = '${path}?imei=${deviceInfo.imei}';
      // 判断是打开本地页面还是跳转到web页面
      openPageByPath(path, "RemoteSettingPage");
    } else if (title == "故障自检") {
      _handleSelfTest(deviceInfo);
    } else if (title == "远程开关") {
      _handleRemoteSwitch();
    } else if (title == "意见与反馈") {
      XLogger.info('意见与反馈');
      openPageByPath("/feedback", "feedback");

    }else {
      openPageByPath("/vipService", "vip");
    }
  }

  /// 导航
  void _navigation() async {
    final availableMaps = await MapLauncher.installedMaps;
    XLogger.info(availableMaps);
    if (availableMaps.isNotEmpty) {
      // 显示bottomSheet
      _showMapSheet(availableMaps);
    } else {
      ToastUtils.showToast('没有安装地图软件');
    }
  }

  /// 显示地图选择
  _showMapSheet(List<AvailableMap> availableMaps) {
    final mapTitleMap = {
      'amap': '高德地图',
      'baidu': '百度地图',
      'google': '谷歌地图',
      'apple': '苹果地图',
      'google': '谷歌地图',
      'tencent': '腾讯地图',
    };
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
          height: availableMaps.length * 60,
          child: ListView.builder(
            itemCount: availableMaps.length,
            itemBuilder: (BuildContext context, int index) {
              final map = availableMaps[index];
              final mapName =
                  mapTitleMap[map.mapType.name.toLowerCase()] ?? map.mapName;
              return ListTile(
                onTap: () {
                  map.showDirections(
                      destination: Coords(monitorData?.latitude ?? 0,
                          monitorData?.longitude ?? 0),
                      destinationTitle: monitorData?.address ?? '');
                  Navigator.pop(context);
                },
                title: Text(mapName),
              );
            },
          ),
        );
      },
    );
  }

  /// 点击菜单
  _onMenuClick(index) async {
    var menu = menuList[index];
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.imei == null || deviceInfo.imei!.isEmpty) {
      ToastUtils.showToast('无设备信息，请先绑定设备或刷新页面获取');
      return;
    }
    // 设备未关机，请开机
    if (deviceInfo.activated == false && deviceInfo.isNineDevice == false) {
      ToastUtils.showSimpleDialog(context,
          title: '提示',
          content: '设备未开机，请开机\n长按开机键3秒或插入充电自动开机',
          confirmTitle: '好的');
      return;
    }
    // 判断是否过期，如果过期，只能打开vip页面、客服页面
    if (deviceInfo.expired == true) {
      if (menu.menuCode != 'vip' && menu.menuCode != 'customerService') {
        // 提示充钱
        ToastUtils.showBuyVip(context, () {
          var vipMenu = getMenuByCode('vip');
          if (vipMenu != null) {
            openPageByPath(vipMenu.path ?? '', vipMenu.menuCode ?? '');
          }
        });
      } else {
        openPageByPath(menu.path ?? '', menu.menuCode ?? '');
      }
      return;
    }
    // 特殊菜单处理
    // 自检
    if (menu.menuCode == 'selfTest') {
      _handleSelfTest(deviceInfo);
      return;
    }
    // 远程重启
    if (menu.menuCode == 'remoteRestart') {
      _handleRemoteRestart();
      return;
    }
    // 远程开关机
    if (menu.menuCode == 'remoteSwitch') {
      _handleRemoteSwitch();
      return;
    }
    // 工作模式
    if (menu.menuCode == 'workMode') {
      _handleWorkMode();
      return;
    }
    // 秒定模式
    if (menu.menuCode == 'instantMode') {
      _handleInstantMode();
      return;
    }
    // 拼接参数
    var path = menu.path ?? '';
    if (path.isEmpty) {
      XLogger.error('菜单配置错误, path: $path');
      // ToastUtils.showToast('菜单配置错误');
      return;
    }
    // if (menu.menuCode == 'vip') {
    // path = 'http://192.168.31.120:10095/vip';
    // WxpayUtils().launch91wl('');
    // return;
    // }
    if (path.contains('?')) {
      path = '${path}&imei=${deviceInfo.imei}';
    } else {
      path = '${path}?imei=${deviceInfo.imei}';
    }
    // 判断是打开本地页面还是跳转到web页面
    openPageByPath(path, menu.menuCode ?? '');
  }

  /// 点击自检
  _handleSelfTest(DeviceInfoVO deviceInfo) async {
    // 加载进度，延迟2s
    ToastUtils.showLoading(status: '正在自检', maskType: EasyLoadingMaskType.black);
    Future.delayed(const Duration(seconds: 2), () {
      if (deviceInfo.isNineDevice == true) {
        ToastUtils.dismissLoading();
        MonitorData monitorData = MonitorData();
        monitorData.batteryPercentage = 100;
        monitorData.deviceStatus = 1;
        monitorData.chargingStatusName = '未充电';
        monitorData.workModeName = '智能模式';
        monitorData.csq = 30;
        monitorData.locationPriority = '优先GPS';
        monitorData.iccid = deviceInfo.imei;
        monitorData.address = '';
        // 时间等于现在的时间减去10秒
        monitorData.lastCommunicationTime = DateUtil.formatDate(
            DateTime.now().subtract(const Duration(seconds: 10)),
            format: 'yyyy-MM-dd HH:mm:ss');
        ;
        ToastUtils.showSelfTestResultDialog(context, monitorData: monitorData);
        return;
      }
      _handleSelfTestData();
    });
  }

  _handleSelfTestData() async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final res = await get<MonitorDataResp, MonitorDataResp>('/monitor/info',
        queryParameters: {'imei': deviceInfo.imei},
        decodeType: MonitorDataResp());
    res.when(success: (MonitorDataResp resp) async {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        // 如果地址为空，则请求接口获取地址
        if (resp.data == null) {
          return;
        }
        var monitorData = resp.data!;
        // 没有经纬度，不请求逆地理编码
        if ((monitorData.address == null || monitorData.address!.isEmpty) &&
            monitorData.latitude != null &&
            monitorData.longitude != null) {
          monitorData.address = await DeviceUtils.reverseGeoCode(
              latitude: monitorData.latitude!,
              longitude: monitorData.longitude!);
        }
        ToastUtils.showSelfTestResultDialog(context, monitorData: monitorData);
      }
    }, failure: (String msg, int code) {
      ToastUtils.dismissLoading();
    });
  }

  /// 点击远程重启
  _handleRemoteRestart() async {
    var cmdCode = 'reset';
    var commandConfig = await _getCommandConfig(cmdCode);
    if (commandConfig == null) {
      return;
    }
    var commandDialogInterface = SimpleCommandDialog(
        scaffoldKey: _scaffoldKey,
        remoteSettingData: commandConfig,
        onConfirm: _onSendCommandClickCallback);
    commandDialogInterface.show(context);
  }

  /// 点击远程开关机
  _handleRemoteSwitch() async {
    var cmdCode = 'Offline';
    var commandConfig = await _getCommandConfig(cmdCode);
    if (commandConfig == null) {
      return;
    }
    var offlineDialog = OfflineDialog(
        scaffoldKey: _scaffoldKey,
        remoteSettingData: commandConfig,
        onConfirm: _onSendCommandClickCallback);
    // 获取用户指令配置
    final userSettingRes = await _getUserSetting(cmdCode);
    userSettingRes.when(success: (resp) {
      if (resp.code == 200) {
        offlineDialog.updateCmdContent(resp.data?.cmdContent ?? '');
        offlineDialog.show(context);
      } else {
        ToastUtils.showToast(resp.msg ?? '获取用户指令配置失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取用户指令配置失败: msg: $msg, code: $code');
      ToastUtils.showToast('获取用户指令配置失败: msg: $msg, code: $code');
    });
  }

  /// 点击工作模式
  _handleWorkMode() async {
    final deviceInfo = ref.read(deviceInfoProvider);

    var cmdCode = 'nmset';
    var commandConfig = await _getCommandConfig(cmdCode);
    if (commandConfig == null) {
      return;
    }
    var workModeDialog = WorkModeDialog(
        scaffoldKey: _scaffoldKey,
        cmdCode: cmdCode,
        imei: deviceInfo.imei,
        onConfirm: _onSendCommandClickCallback);
    // 获取用户指令配置
    final userSettingRes = await _getUserSetting(cmdCode);
    userSettingRes.when(success: (resp) {
      if (resp.code == 200) {
        workModeDialog.updateCmdContent(resp.data?.cmdContent ?? '');
        workModeDialog.show(context);
      } else {
        ToastUtils.showToast(resp.msg ?? '获取用户指令配置失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取用户指令配置失败: msg: $msg, code: $code');
      ToastUtils.showToast('获取用户指令配置失败: msg: $msg, code: $code');
    });
  }

  /// 点击秒定模式
  _handleInstantMode() async {
    var dialog = InstantModeDialog(onConfirm: _onInstantModeConfirm);
    dialog.show(context);
  }

  _onInstantModeConfirm() {
    // 判断秒定模式是否到期，若已到期就跳到【增值服务页面-秒定模式】，没到期就发指令nmset,0,10给设备
    final deviceInfo = ref.watch(deviceInfoProvider);
    // 检查秒定模式是否到期
    if (deviceInfo.isInstantModeExpired() == true) {
      // 秒定模式已到期,跳转到增值服务页面
      var vipMenu = getMenuByCode('valueAddedService');
      if (vipMenu != null) {
        openPageByPath(vipMenu.path ?? '', vipMenu.menuCode ?? '');
      } else {
        ToastUtils.showToast('无法找到增值服务页面');
      }
    } else {
      // 秒定模式未到期，发送指令nmset,0,10给设备
      _onSendCommandClickCallback('nmset,0,10');
    }
  }

  Future<Result<GetSettingResp>> _getUserSetting(String cmdCode) async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final postData = {
      'imei': deviceInfo.imei,
      'cmdCode': cmdCode,
    };
    final res = await post<GetSettingResp, GetSettingResp>(
        '/command/getSetting',
        data: postData,
        decodeType: GetSettingResp());
    return res;
  }

  _onSendCommandClickCallback(String cmdContent) async {
    XLogger.info('发送指令: $cmdContent');
    final deviceInfo = ref.read(deviceInfoProvider);
    final postData = {
      'imei': deviceInfo.imei,
      'content': cmdContent,
      'cmdCode': cmdContent.split(',')[0],
    };
    // 一键重启的指令作特殊处理，实际换成立即定位指令
    if (cmdContent == 'reset') {
      postData['cmdCode'] = 'c';
      postData['content'] = 'c';
    }
    ToastUtils.showLoading(status: '发送中...');
    final res = await post<BaseResp, BaseResp>('/command/send',
        data: postData, decodeType: BaseResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        ToastUtils.showToast('发送成功');
      } else {
        ToastUtils.showToast(resp.msg ?? '发送失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('发送指令失败: msg: $msg, code: $code');
      ToastUtils.showToast('发送指令失败: msg: $msg, code: $code');
    });
  }

  /// 点击查看设备信息
  _goDeviceInfoPage() {
    context.push(RouterManager.deviceInfo);
  }

  _doPullDownRefresh() async {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    await _refreshDeviceInfo(deviceInfo.imei ?? '');
    await getMonitorData();
    _refreshController.finishRefresh();
  }

  Future _refreshDeviceInfo(String imei) async {
    XLogger.debug('刷新设备信息 --- ');
    var res = await get<HomeDeviceInfoResp, HomeDeviceInfoResp>(
        '/home/deviceInfo',
        queryParameters: {'imei': imei},
        decodeType: HomeDeviceInfoResp());
    res.when(
        success: (HomeDeviceInfoResp resp) async {
          showLoading = false;
          if (resp.code == 200) {

            userDeviceCount = resp.data?.deviceCount ?? 0;
            if (resp.data == null || resp.data!.deviceInfo == null) {
               ref.read(deviceInfoProvider.notifier).removeDeviceInfo();
              setState(() {
                hasThing = false;
              });
              return;
            }
            var deviceInfoVO = resp.data!.deviceInfo!;
            DeviceInfoVO device = ref.watch(deviceInfoProvider);
            int? deviceMode = device.deviceMode;
            deviceInfoVO.deviceMode = deviceMode;
            ref.read(deviceInfoProvider.notifier).setDeviceInfo(deviceInfoVO);
            setState(() {
              hasThing = true;
            });
            // 如果设备未过期，则停止定时器
            if (deviceInfoVO.expired == true) {
              if (_timerUtil == null || !_timerUtil!.isActive()) {
                _startRefreshInfo();
              }
            } else {
              _timerUtil?.cancel();
            }
            // 判断是否需要弹出充值提示
            if (deviceInfoVO.showRechargeTip == true &&
                !hasShowRechargeDialog) {
              showBuyVipDialog();
            }
          } else if (resp.code == 60001) {
            // 无设备信息，移除显示设备
            ref.read(deviceInfoProvider.notifier).removeDeviceInfo();
            setState(() {
              hasThing = false;
            });
          } else {
            // setState(() {
            //   hasThing = false;
            // });
            XLogger.debug(resp.msg);
          }
        },
        failure: (String msg, int code) {});
  }

  /// 是否需要修改密码
  _isNeedChangePassword() {
    var needChangePassword = SpUtil.getBool('needChangePassword');
    if (needChangePassword == null || !needChangePassword) {
      return;
    }
    context.push(RouterManager.changePasswordLogon);
  }

  _startRefreshInfo() {
    GlobalConfigData globalConfig =
        ref.watch(globalStateProvider).globalConfig!;
    if (globalConfig.autoRefresh == false) {
      return;
    }
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.imei == null || deviceInfo.imei!.isEmpty) {
      return;
    }
    // 未激活设备、到期设备，开启定时获取设备信息
    if (deviceInfo.activated == true && deviceInfo.expired == false) {
      return;
    }
    // 开启定时刷新
    _startTimer();
  }

  _startTimer() {
    GlobalConfigData globalConfig =
        ref.watch(globalStateProvider).globalConfig!;
    if (_timerUtil != null) {
      _timerUtil!.cancel();
    }
    _timerUtil = TimerUtil();
    _timerUtil?.setInterval(globalConfig.refreshInterval!);
    _timerUtil?.setOnTimerTickCallback((int value) async {
      XLogger.debug('定时刷新设备信息 --- ');
      DeviceInfoVO newDeviceInfo = ref.watch(deviceInfoProvider);
      _refreshDeviceInfo(newDeviceInfo.imei!);
    });
    _timerUtil?.startTimer();
  }

  Future<RemoteSettingData?> _getCommandConfig(String cmdCode) async {
    final queryParams = {
      'cmdCode': cmdCode,
    };
    final res = await get<CommandConfigResp, CommandConfigResp>(
        '/command/config',
        queryParameters: queryParams,
        decodeType: CommandConfigResp());
    return res.when<RemoteSettingData?>(success: (CommandConfigResp resp) {
      if (resp.code == 200) {
        return resp.data!;
      }
      return null;
    }, failure: (String msg, int code) {
      return null;
    });
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      ref.watch(updateIconProvider.notifier).addListener((state) async {
        setState(() {});
      });
      ref.watch(alarmDataProvider.notifier).addListener((state) async {
        setState(() {});
      });
      ref.watch(monitorDataProvider.notifier).addListener((state) async {
        setState(() {});
      });

      // UpgradeUtils.checkUpdate(context, fromPage: 'home');
      // UpgradeUtils.testUpdate();
      // JPushUtils.initJPush();
      // 先去掉修改密码的判断
      // _isNeedChangePassword();
      // 获取全局配置
      await AppStart.getGlobalConfig(ref);
      await _doPullDownRefresh();
      // 获取菜单列表配置
      await fetchMenuList();
      Future.delayed(const Duration(seconds: 5), () {
        PermissionManager.requestNotificationPermissions();
        _startRefreshInfo();
      });
      ref.watch(deviceInfoProvider.notifier).addListener((state) async {
        XLogger.info('设备信息变化 --- ${state.imei}');
        if (!mounted) return;
        if (state.imei == null || state.imei!.isEmpty) {
          return;
        }
        // 切换设别时，重新获取菜单列表
        await fetchMenuList();
        menuList = List.from(menuListResp);
        if (state.vipService == false) {
          menuList =
              menuList.where((element) => element.menuCode != 'vip').toList();
        }
        if (state.valueAddedService == false) {
          menuList = menuList
              .where((element) => element.menuCode != 'valueAddedService')
              .toList();
        }
        if (mounted) setState(() {});
      });
    });
    super.initState();
    _refreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
  }

  @override
  void dispose() {
    super.dispose();
    _timerUtil?.cancel();
    _refreshController.dispose();
  }

  /// 保存页面状态
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    monitorData = ref.read(monitorDataProvider);
    XLogger.info((monitorData?.batteryPercentage));
    return Scaffold(
        key: _scaffoldKey,
        body: Container(
          height: double.infinity,
          decoration: BoxDecoration(
              image: DecorationImage(
            image: AssetImage('assets/images/controCenterBg.png'),
            fit: BoxFit.cover,
          )),
          child: EasyRefresh(
              controller: _refreshController,
              onRefresh: () async {
                _doPullDownRefresh();
              },
              child: showLoading ? _buildLoading() : _buildBody()),
        ));
  }

  Widget buildMsg() {
    final alarmData = ref.read(alarmDataProvider);
    return GestureDetector(
      onTap: (){
        context.push(RouterManager.msg);
      },
      child: Container(
        margin: EdgeInsets.only(top: 10),
        padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(4),
            border: Border.all(width: 1, color: Colors.black)),
        child: Row(
          children: [
            Image.asset("assets/images/home/icon_notice.png",
                width: 16, height: 16),
            SizedBox(width: 4),
            Expanded(child: lpText(
                "您的设备${DateUtil.formatDate(alarmData.occurTime, format: 'yyyy/MM/dd HH:mm:ss')}${alarmData.warnDesc}",
                size: 16,
                maxLine: 1,
                textOverflow: TextOverflow.ellipsis))
          ],
        ),
      ),
    );
  }
}
